package com.lepu.app.fun.my;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.app.application.MyApplication;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.core.lib.widget.GoogleRefreshLayout.OnScrollListener;
import com.lepu.app.fun.my.adapter.AdapterMyUserInfoHospital;
import com.lepu.app.fun.my.bean.BeanMyUserInfoHospital;
import com.lepu.pasm.R;

public class MyUserInfoHospitalActivity extends BaseFragmentActivity implements
		AsyncRequest, OnRefreshListener, OnLoadListener,OnEditorActionListener,OnScrollListener {

	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_DATA_MORE_SUCCESS = 12;
	private static final int MSG_DATA_MORE_FAIL = 13;

	public GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mDataListView = null;
	private AdapterMyUserInfoHospital mDataAdapter = null;
	private ArrayList<BeanMyUserInfoHospital> mDataArrayList = null;
	private int mCurrentPage = 1;
	
	private String mSearchKey = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_userinfo_hospital_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}
	
	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (actionId) {
		case EditorInfo.IME_ACTION_SEARCH:
			
			search();
			break;

		default:
			break;
		}
		return true;
	}

	/**
	 * 初始化方法
	 */
	@SuppressWarnings("deprecation")
	private void init() {

		mDataListView = (ListView) findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setOnScrollListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
				R.color.color_listview_refresh_2,
				R.color.color_listview_refresh_3,
				R.color.color_listview_refresh_4);
		mDataListView.setOnItemClickListener(mOnItemClickListener);
		
		EditText contentEditText = (EditText) findViewById(R.id.contentEditText);
		contentEditText.setFilters(new InputFilter[]{new EmojiFilter(),new InputFilter.LengthFilter(11)});
		contentEditText.setOnEditorActionListener(this);
		contentEditText.addTextChangedListener(mTextWatcher);
	}
	
	OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			BeanMyUserInfoHospital item = mDataArrayList.get(position);
			MyUserInfoActivity instance = (MyUserInfoActivity) AppManager.getAppManager().getActivity(MyUserInfoActivity.class);
			if(instance != null)
			{
				finish(true);
				instance.setHospital(item);
			}
		}
	};
	
	TextWatcher mTextWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
			
			search();
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {

		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	};
	
	private void search()
	{
		EditText contentEditText = (EditText) findViewById(R.id.contentEditText);
		String content = contentEditText.getText().toString().trim();
		if(TextUtils.isEmpty(content))
		{
			UIHelper.showToast(this, "请输入关键字搜索");
			return;
		}
		
		mSearchKey = content;
		mGoogleRefreshLayout.setRefreshing(true);
		request(false);
	}

	// 请求数据
	public void request(boolean isMore) {

		String request = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
		} else {
			request = REQUEST_DATA;
			mCurrentPage = page;
		}

		String url = Setting.getMyUserInfoHospitalUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);

			params.put("InstitutionName", mSearchKey);
			
			params.put("PageIndex", page);
			params.put("PageSize", Setting.PAGE_SIZE);
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post(url, map, null, this, request, true, false, true);
	}

	public void viewClick(View view) {
		int rid = view.getId();
		switch (rid) {
		case R.id.cancelTextView:

			finish(true);
			break;

		default:
			break;
		}
	}

	@Override
	public void onLoad() {
		request(true);
	}

	@Override
	public void onRefresh() {
		
		if(TextUtils.isEmpty(mSearchKey))
		{
			mGoogleRefreshLayout.setRefreshing(false);
			return;
		}
		request(false);
	}
	
	@SuppressLint("HandlerLeak") 
	Handler mHandler = new Handler(){
		public void handleMessage(Message msg) {
			
			switch (msg.what) {
			case MSG_DATA_SUCCESS:

				@SuppressWarnings("unchecked")
				ArrayList<BeanMyUserInfoHospital> dataList = (ArrayList<BeanMyUserInfoHospital>) msg.obj;
				if (dataList != null && dataList.size() > 0) {

					mDataArrayList = dataList;
				} else {
					UIHelper.showToast(MyApplication.getInstance(),
							R.string.no_data);

					if (mDataArrayList != null && mDataArrayList.size() > 0) {
						mDataArrayList.clear();
					}
				}

				if (mDataArrayList == null) {
					mDataArrayList = new ArrayList<BeanMyUserInfoHospital>();
				}

				ImageView tempImageView = new ImageView(MyUserInfoHospitalActivity.this);
				mDataListView.addHeaderView(tempImageView);

				mDataAdapter = new AdapterMyUserInfoHospital(MyUserInfoHospitalActivity.this,
						mDataArrayList);
				mDataListView.setAdapter(mDataAdapter);

				mDataListView.removeHeaderView(tempImageView);

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);

				if (mDataArrayList != null && mDataArrayList.size() > 0) {
					if (mDataArrayList.size() < Setting.PAGE_SIZE) {
						mGoogleRefreshLayout.setLoadMoreFinish(true);
					}
				}else{
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}
				break;
			case MSG_DATA_FAIL:

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);
				break;
			case MSG_DATA_MORE_SUCCESS:

				@SuppressWarnings("unchecked")
				ArrayList<BeanMyUserInfoHospital> dataMoreList = (ArrayList<BeanMyUserInfoHospital>) msg.obj;
				if (dataMoreList != null && dataMoreList.size() > 0) {
					mDataAdapter.notifyDataSetChanged();

					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					UIHelper.showToast(MyApplication.getInstance(),
							R.string.no_data_more);
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_MORE_FAIL:

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;

			default:
				break;
			}
			
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			// 解析json data
			ArrayList<BeanMyUserInfoHospital> dataArraylist = BeanMyUserInfoHospital
					.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			// 解析json data more
			ArrayList<BeanMyUserInfoHospital> dataMoreArraylist = BeanMyUserInfoHospital
					.parseJsonData((String) data);

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
				for (int i = 0; i < dataMoreArraylist.size(); i++) {
					BeanMyUserInfoHospital item = dataMoreArraylist.get(i);
					mDataArrayList.add(item);
				}
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		} 
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if(object.equals(REQUEST_DATA))
		{
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		}else if(object.equals(REQUEST_DATA_MORE)){
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		UtilityBase.closeSoftInput(this);
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		
	}

}
